package com.yangtu.nearbyshop.merc.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yangtu.nearbyshop.core.util.DateTimeUtil;
import com.yangtu.nearbyshop.core.util.ResponseUtil;
import com.yangtu.nearbyshop.db.domain.*;
import com.yangtu.nearbyshop.db.service.NearbyshopMercService;
import com.yangtu.nearbyshop.db.service.itf.*;
import com.yangtu.nearbyshop.db.util.OrderUtil;
import com.yangtu.nearbyshop.merc.annotation.LoginMerc;
import com.yangtu.nearbyshop.merc.service.MercTokenManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.yangtu.nearbyshop.merc.service.MercOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/merc/order")
@Validated
public class MercOrderController {
    private final Log logger = LogFactory.getLog(MercOrderController.class);

    @Autowired
    private MercOrderService mercOrderService;

    @Autowired
    private INearbyshopOrderService orderService;

    @Autowired
    private INearbyshopMercRebateSettleService rebateSettleService;

    @Autowired
    private INearbyshopMercRebateService rebateService;

    @Autowired
    private INearbyshopMercSettleService settleService;

    @Autowired
    private NearbyshopMercService mercService;

    /**
     * 订单列表
     *
     * @param mercId   用户ID
     * @param showType 订单信息
     * @param page     分页页数
     * @param size     分页大小
     * @return 订单列表
     */
/*    @GetMapping("list")
    public Object list(@LoginMerc Integer mercId,
                       @RequestParam(defaultValue = "0") Integer showType,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer size) {
        return mercOrderService.list(MercTokenManager.getMercNo(mercId), showType, page, size);
    }*/

    /**
     * 订单详情
     *
     * @param mercId  用户ID
     * @param orderId 订单ID
     * @return 订单详情
     */
    @GetMapping("detail")
    public Object detail(@LoginMerc Integer mercId, @NotNull Integer orderId) {
        return mercOrderService.detail(mercId, orderId);
    }

    /**
     * 订单申请退款
     *
     * @param mercId 用户ID
     * @param body   订单信息，{ orderId：xxx }
     * @return 订单退款操作结果
     */
    @PostMapping("refund")
    public Object refund(@LoginMerc Integer mercId, @RequestBody String body) {
        return mercOrderService.refund(mercId, body);
    }

    /**
     * 确认收货
     *
     * @param mercId 用户ID
     * @param body   订单信息，{ orderId：xxx }
     * @return 订单操作结果
     */
    @PostMapping("confirm")
    public Object confirm(@LoginMerc Integer mercId, @RequestBody String body) {
        return mercOrderService.confirm(mercId, body);
    }



    /**
     * 商户收益明细
     *
     * @param mercId 用户ID
     * @param startDt   起始时间
     * @param endDt   结束时间
     * @param page   页数
     * @param size   每页条数
     * @return 订单操作结果
     */
    @GetMapping("mercProfit")
    public Object mercProfit(@LoginMerc Integer mercId,
                             String startDt,
                             String endDt,
                             @RequestParam(defaultValue = "1") Integer page,
                             @RequestParam(defaultValue = "10") Integer size) {
        return mercOrderService.profitList(MercTokenManager.getMercNo(mercId), startDt, endDt, page, size);
    }

    /**
     * 商户推荐收益明细
     *
     * @param mercId 用户ID
     * @param startDt   起始时间
     * @param endDt   结束时间
     * @return 订单操作结果
     */
    @GetMapping("mercReferProfit")
    public Object mercReferProfit(@LoginMerc Integer mercId,
                             String startDt,
                             String endDt) {
        return mercOrderService.referProfitList(MercTokenManager.getMercNo(mercId), startDt, endDt);
    }

    /**
     * 订单提货
     *
     * @param mercId 用户ID
     * @param body   订单信息，{ orderIds：xxx }  多个订单逗号隔开
     * @return 订单操作结果
     */
    @PostMapping("taken")
    public Object taken(@LoginMerc Integer mercId, @RequestBody String body) {
        return mercOrderService.taken(mercId, body);
    }

    /**
     * 发布到货提醒
     *
     * @param mercId 用户ID
     * @param body   订单信息，{ orderIds：xxx }  多个订单逗号隔开
     * @return 订单操作结果
     */
    @PostMapping("sendAriveMsg")
    public Object sendAriveMsg(@LoginMerc Integer mercId, @RequestBody String body) {
        return mercOrderService.sendAriveMsg(mercId, body);
    }

    /**
     * 订单列表新
     *
     * @param mercId   用户ID
     * @param showType 订单信息  6：未发货（已付款，已采购+未采购，未发货）
     *                          7：已发货（已付款+已退款，已采购，已发货）
     *                          8：已完成（已提货+已收货，已采购，已发货）
     * @param page     分页页数
     * @param size     分页大小
     * @return 订单列表
     */
    @GetMapping("list")
    public Object list(@LoginMerc Integer mercId,
                       @RequestParam(defaultValue = "0") Integer showType,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer size) {
        Page<NearbyshopOrder2> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(size);
        IPage<NearbyshopOrder2> pList = null;
        String mercNo = MercTokenManager.getMercNo(mercId);
        if(showType == 6){
            pList = orderService.page(pageVo,new QueryWrapper<NearbyshopOrder2>()
                    .eq("merc_no",mercNo)
                    .eq("order_status", OrderUtil.STATUS_PAY)
                    .orderByDesc("add_time"));
        }else if(showType == 7){
            pList = orderService.page(pageVo,new QueryWrapper<NearbyshopOrder2>()
                    .eq("merc_no",mercNo)
                    .in("order_status", OrderUtil.STATUS_SHIP)
                    .orderByDesc("add_time"));
        }else if(showType == 8){
            pList = orderService.page(pageVo,new QueryWrapper<NearbyshopOrder2>()
                    .eq("merc_no",mercNo)
                    .in("order_status", OrderUtil.STATUS_CONFIRM,
                            OrderUtil.STATUS_AUTO_CONFIRM,OrderUtil.STATUS_REFUND_CONFIRM,OrderUtil.STATUS_REFUND)
                    .orderByDesc("add_time"));
        }

//        Map<String, Object> data = new HashMap<>();
//        data.put("total", pList.getTotal());
//        data.put("totalPages", pList.getPages());
//        data.put("items", pList.getRecords());

        Map<String, Object> result = new HashMap<>();
        result.put("total", pList.getTotal());
        result.put("items", mercOrderService.listNew((List<NearbyshopOrder2>)pList.getRecords()));
        result.put("totalPages", pList.getPages());

        return ResponseUtil.ok(result);
    }

    /**
     * @api {GET} /merc/order/dailyRebate 日返利
     * @apiName order dailyRebate
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} mercId 团长ID
     * @apiParam {int} page 页码
     * @apiParam {int} size 每页数量
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("/dailyRebate")
    public Object dailyRebate(@LoginMerc Integer mercId,
                              @RequestParam(defaultValue = "1") Integer page,
                              @RequestParam(defaultValue = "10") Integer size){
        Page<NearbyshopMercRebateSettle> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(size);
        String mercNo = MercTokenManager.getMercNo(mercId);
        IPage<NearbyshopMercRebateSettle> pList = rebateSettleService.getDailyRebateSettle(pageVo,
                null,mercNo,null,null);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }

    /**
     * @api {GET} /merc/order/rebateDetail 日返利明细
     * @apiName order rebateDetail
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {String} startTime 开始时间
     * @apiParam {String} endTime 结束时间
     * @apiParam {int} page 页码
     * @apiParam {int} size 每页数量
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("/rebateDetail")
    public Object rebateDetail(@LoginMerc Integer mercId,String startTime,String endTime,
                              @RequestParam(defaultValue = "1") Integer page,
                              @RequestParam(defaultValue = "10") Integer size){
       /* NearbyshopMercRebateSettle rebateSettle = rebateSettleService.getById(id);
        if(rebateSettle == null){
            return ResponseUtil.fail("日返利数据不存在");
        }
        Date date = rebateSettle.getAddTime();
        String dateStr = DateTimeUtil.getDateDisplayString(date);*/
        /*String startTime = dateStr + " 00:00:00";
        String endTime = dateStr + " 23:59:59";*/
        Page<NearbyshopMercRebate> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(size);
        String mercNo = MercTokenManager.getMercNo(mercId);
        IPage<NearbyshopMercRebate> pList = rebateService.getTimeRebate(pageVo,
                null,mercNo,startTime,endTime);

        String allRebate = rebateService.countAllRebate(mercNo,null,null);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        data.put("allRebate", allRebate);
        return ResponseUtil.ok(data);
    }

    /**
     * @api {GET} /merc/order/weekSettle 周营业额
     * @apiName order weekSettle
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {int} mercId 团长ID
     * @apiParam {int} page 页码
     * @apiParam {int} size 每页数量
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("/weekSettle")
    public Object weekSettle(@LoginMerc Integer mercId,
                               @RequestParam(defaultValue = "1") Integer page,
                               @RequestParam(defaultValue = "10") Integer size){
        Page<NearbyshopMercSettle> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(size);
        String mercNo = MercTokenManager.getMercNo(mercId);
        IPage<NearbyshopMercSettle> pList = settleService.getMercSettleList(pageVo,mercNo);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }

    /**
     * @api {GET} /merc/order/rebateDay 日返利
     * @apiName order rebateDay
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {String} orgNo 随行付编号
     * @apiParam {int} page 页码
     * @apiParam {int} size 每页数量
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("/rebateDay")
    public Object rebateDay(@NotNull String orgNo,
                            @RequestParam(defaultValue = "1") Integer page,
                            @RequestParam(defaultValue = "10") Integer size){
        Page<NearbyshopMercRebateSettle> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(size);
        NearbyshopMerc merc = mercService.queryByOrgNo(orgNo);
        if(null == merc){
            return ResponseUtil.fail("商户不存在");
        }
        IPage<NearbyshopMercRebateSettle> pList = rebateSettleService.getDailyRebateSettle(pageVo,
                null,merc.getMercNo(),null,null);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }

    /**
     * @api {GET} /merc/order/rebateAll 所有日返利
     * @apiName order rebateAll
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {String} orgNo 随行付编号
     * @apiParam {int} [page] 页码
     * @apiParam {int} [size] 每页数量
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("/rebateAll")
    public Object rebateAll(@NotNull String orgNo){
        Page<NearbyshopMercRebateSettle> pageVo = new Page<>();
        pageVo.setCurrent(1);
        pageVo.setSize(1000000);
        NearbyshopMerc merc = mercService.queryByOrgNo(orgNo);
        if(null == merc){
            return ResponseUtil.fail("商户不存在");
        }
        IPage<NearbyshopMercRebateSettle> pList = rebateSettleService.getDailyRebateSettle(pageVo,
                null,merc.getMercNo(),null,null);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        return ResponseUtil.ok(data);
    }

    /**
     * @api {GET} /merc/order/rebateDayDetail 日返利明细
     * @apiName order rebateDayDetail
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {String} startTime 开始时间
     * @apiParam {String} endTime 结束时间
     * @apiParam {int} page 页码
     * @apiParam {int} size 每页数量
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("/rebateDayDetail")
    public Object rebateDayDetail(@NotNull String orgNo,String startTime,String endTime,
                                  @RequestParam(defaultValue = "1") Integer page,
                                  @RequestParam(defaultValue = "10") Integer size){
        Page<NearbyshopMercRebate> pageVo = new Page<>();
        pageVo.setCurrent(page);
        pageVo.setSize(size);
        NearbyshopMerc merc = mercService.queryByOrgNo(orgNo);
        IPage<NearbyshopMercRebate> pList = rebateService.getTimeRebate(pageVo,
                null,merc.getMercNo(),startTime,endTime);

        String allRebate = rebateService.countAllRebate(merc.getMercNo(),null,null);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        data.put("allRebate", allRebate);
        return ResponseUtil.ok(data);
    }

    /**
     * @api {GET} /merc/order/rebateDayAll 所有日返利
     * @apiName order rebateDayAll
     * @apiGroup order
     * @apiVersion 1.0.0
     * @apiDescription 接口负责人-王雷
     *
     * @apiParam {String} startTime 开始时间
     * @apiParam {String} endTime 结束时间
     * @apiParam {String} orgNo 随行付编号
     * @apiParam {int} [page] 页码
     * @apiParam {int} [size] 每页数量
     *
     * @apiSuccess {int} code 结果码 0:正常返回,-1服务异常,1业务异常
     * @apiSuccess {String} message 前端提示消息
     * @apiSuccess {Object} value 结果集
     * @apiSuccess {String} bizCode 业务异常码
     * @apiSuccessExample Success-Response:
     * HTTP/1.1 200 OK
    {
     *     "errno": 0,
     *     "errmsg": "成功"
     * }
     */
    @GetMapping("/rebateDayAll")
    public Object rebateDayAll(@NotNull String orgNo,String startTime,String endTime){
        Page<NearbyshopMercRebate> pageVo = new Page<>();
        pageVo.setCurrent(1);
        pageVo.setSize(1000000);
        NearbyshopMerc merc = mercService.queryByOrgNo(orgNo);
        IPage<NearbyshopMercRebate> pList = rebateService.getTimeRebate(pageVo,
                null,merc.getMercNo(),startTime,endTime);

        String allRebate = rebateService.countAllRebate(merc.getMercNo(),null,null);
        Map<String, Object> data = new HashMap<>();
        data.put("total", pList.getTotal());
        data.put("items", pList.getRecords());
        data.put("allRebate", allRebate);
        return ResponseUtil.ok(data);
    }

}
